package cn.zhentao.controller;

import cn.zhentao.ExceptionQueryDTO;
import cn.zhentao.mapper.*;
import cn.zhentao.pojo.*;
import cn.zhentao.service.*;
import cn.zhentao.util.JwtService;
import cn.zhentao.util.Result;
import cn.zhentao.util.ThreadLocalUtil;
import cn.zhentao.vo.QueryPage;
import cn.zhentao.vo.TaskDetailsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("delivery")
public class DeliveryController {
    @Autowired
    private ExceptionReportMapper exceptionReportMapper;
    //配送员
    @Autowired
    private IDeliveryMenService deliveryMenService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IOrderAssignmentsService orderAssignmentsService;
    @Autowired
    private IDeliveryTasksService deliveryTasksService;
    @Autowired
    private IPriorityLevelsService priorityLevelsService;


    @Autowired
    private IDeliverymanNotificationsService deliverymanNotificationsService;
    @Autowired
    private DeliveryMenMapper deliveryMenMapper;
    @Autowired
    private IVTaskPackagesService ivTaskPackagesService;
    @Autowired
    private IVTaskPackageOrdersService ivTaskPackageOrdersService;
    @Autowired
    private VTaskPackageOrdersMapper  vTaskPackageOrdersMapper;
    @Autowired
    private IDeliverymanNotificationsService notificationService;
    @Autowired
    private ExceptionImageMapper exceptionImageMapper;



    @GetMapping("getNotifications")
    public Result getNotifications(){
        QueryWrapper<DeliverymanNotifications> deliverymanNotificationsQueryWrapper = new QueryWrapper<>();
        String token = ThreadLocalUtil.get();
        Map<String, Object> map = JwtService.getClaimsMap(token);
        DeliveryMen men = deliveryMenMapper.selectOne(new QueryWrapper<DeliveryMen>().eq("user_id", (Integer)map.get("id")));
        deliverymanNotificationsQueryWrapper.eq("deliveryman_id",men.getId());
        List<DeliverymanNotifications> list = deliverymanNotificationsService.list(deliverymanNotificationsQueryWrapper);
        return Result.OK(list);
    }

    @RequestMapping("findAllTask")
    public Result findAllTask(@RequestBody QueryPage queryPage){
       List<TaskDetailsVo> list = deliveryTasksService.findAllTask(queryPage);
       return Result.OK(list);
   }
   @RequestMapping("findAllTaskGroup")
   public Result findAllTaskGroup(@RequestBody QueryPage queryPage){
       List<TaskDetailsVo> list = deliveryTasksService.findAllTaskGroup(queryPage);
       return Result.OK(list);
   }
   @RequestMapping("findAllLeavel")
    public Result findAllLeavel(){
       List<PriorityLevels> list = priorityLevelsService.list();
       return Result.OK(list);
   }
   @RequestMapping("getPendingTaskPackages")
    public Result pendingTaskPackages(){
       List<VTaskPackages> packageStatus = ivTaskPackagesService.list();
       for (VTaskPackages taskPackages : packageStatus) {
           String orderNumbers = taskPackages.getOrderNumbers();
           String[] strings = orderNumbers.split(",");
           taskPackages.setOrders(strings);
       }
       return Result.OK(packageStatus);
   }
    // 异常上报主表
    @PostMapping("/exception")
    public Result reportException(@RequestBody ExceptionReport dto) {
        String reportId = UUID.randomUUID().toString().replaceAll("-", "");
        ExceptionReport report = new ExceptionReport();
        report.setId(reportId);
        report.setTrackingId(dto.getTrackingId());
        report.setCustomer(dto.getCustomer());
        report.setType(dto.getType());
        report.setSeverity(dto.getSeverity());
        report.setDescription(dto.getDescription());
        report.setStatus("未处理");
        report.setReportTime(new Date());
        // ... 其他字段赋值

        exceptionReportMapper.insert(report);

        // 返回主键ID，前端用于图片上传
        Map<String, Object> data = new HashMap<>();
        data.put("id", reportId);
        return Result.OK(data);
    }
   @RequestMapping("task-package")
    public Result deliveringTaskPackages(String PackageId){
       Result result = pendingTaskPackages();
       System.err.println("---------------------------------"+result);
       List<VTaskPackageOrders> packageId = ivTaskPackageOrdersService.list(new QueryWrapper<VTaskPackageOrders>().eq("package_id", PackageId));
       List<VTaskPackages> list = (List<VTaskPackages>) result.getData();
       List<VTaskPackageOrders> list1 = new ArrayList<>();
       for (VTaskPackages vTaskPackages : list) {
           if (vTaskPackages.getPackageId().equals(PackageId)) {
               String[] orders = vTaskPackages.getOrders();
               for (String order : orders) {
                   VTaskPackageOrders orderNumber = vTaskPackageOrdersMapper.selectOne(new QueryWrapper<VTaskPackageOrders>().eq("order_number", order));
                   System.err.println("-------------------------------------------------------"+orderNumber);
                   list1.add(orderNumber);
               }
           }
       }
       if(packageId!=null && packageId.size()>0){
           System.err.println("----------------------------------"+list1);
           packageId.get(0).setOrders(list1);
           return Result.OK(packageId.get(0));
       }else{
           return Result.ERROR("查询错误,此id下有可能不在");
       }
   }

    @GetMapping("/detail")
    public Result detail(@RequestParam String id) {
        ExceptionReport report = exceptionReportMapper.selectById(id);
        List<ExceptionImage> images = exceptionImageMapper.selectList(
                new QueryWrapper<ExceptionImage>().eq("report_id", id)
        );
        Map<String, Object> data = new HashMap<>();
        data.put("report", report);
        data.put("images", images.stream().map(ExceptionImage::getImageUrl).collect(Collectors.toList()));
        // 可加留言等
        return Result.OK(data);
    }
    @PostMapping("/list")
    public Result list(@RequestBody ExceptionQueryDTO dto) {
        Page<ExceptionReport> page = new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<ExceptionReport> wrapper = new QueryWrapper<>();

        // 动态拼接条件
        if (StringUtils.hasText(dto.getType())) {
            wrapper.eq("type", dto.getType());
        }
        if (StringUtils.hasText(dto.getSeverity())) {
            wrapper.eq("severity", dto.getSeverity());
        }
        if (StringUtils.hasText(dto.getKeyword())) {
            wrapper.and(w -> w.like("id", dto.getKeyword())
                    .or().like("tracking_id", dto.getKeyword())
                    .or().like("customer", dto.getKeyword()));
        }
        // ... 其他条件

        IPage<ExceptionReport> result = exceptionReportMapper.selectPage(page, wrapper);
        return Result.OK(result);
    }
    @PostMapping("/process")
    public Result process(@RequestBody Map<String, Object> params) {
        String id = (String) params.get("id");
        ExceptionReport update = new ExceptionReport();
        update.setId(id);
        update.setAction((String) params.get("action"));
        update.setResponsible((String) params.get("responsible"));
        update.setExpectedDate(params.get("expectedDate") != null ? LocalDate.parse((String) params.get("expectedDate")) : null);
        update.setNotes((String) params.get("notes"));
        update.setStatus("已解决");
        exceptionReportMapper.updateById(update);
        return Result.OK();
    }
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String path = "C:/Users/86156/Desktop/MyProect/myProjectImages/images/pic/";
        int i = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(i);
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        String newname = name+extname;
        File f = new File(path,newname);
        file.transferTo(f);
        String url = "http://localhost:7000/images/pic/"+newname;
        return Result.OK(url);
    }
    @PostMapping("/uploadImage")
    public Result uploadExceptionImage(@RequestParam("report_id") String reportId,
                                       @RequestParam("image") MultipartFile file) throws IOException {
        // 1. 保存图片到本地
        String originalFilename = file.getOriginalFilename();
        String path = "C:/Users/86156/Desktop/MyProect/myProjectImages/images/pic/";
        int i = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(i); // .jpg
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        String newname = name + extname;
        File f = new File(path, newname);
        file.transferTo(f);

        // 2. 生成图片URL
        String url = "http://localhost:7000/images/pic/" + newname;

        // 3. 插入图片表
        ExceptionImage img = new ExceptionImage();
        img.setReportId(reportId);
        img.setImageUrl(url);
        exceptionImageMapper.insert(img);

        return Result.OK(url);
    }
    @RequestMapping("task-packages") // 注意：我们把 @GetMapping 改为了 @PostMapping
    public Result getTaskPackages(@RequestBody TaskPackageQuery query) {

        // 1. 创建 MyBatis-Plus 的分页对象
        Page<VTaskPackages> page = new Page<>(query.getPage(), query.getSize());

        // 2. 创建查询条件构造器 (逻辑和之前一样)
        QueryWrapper<VTaskPackages> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(query.getStatus())) {
            queryWrapper.eq("package_status", mapStatusToCode(query.getStatus()));
        }
        if (StringUtils.hasText(query.getPackageId())) {
            queryWrapper.like("package_id", query.getPackageId());
        }
        if (StringUtils.hasText(query.getDeliveryArea())) {
            queryWrapper.like("delivery_area", query.getDeliveryArea());
        }
        if (StringUtils.hasText(query.getPriority())) {
            queryWrapper.eq("priority", query.getPriority());
        }
        queryWrapper.orderByDesc("created_at"); // 按创建时间降序排序

        // 3. 执行分页查询！
        // .page() 方法会自动生成分页SQL，并返回一个包含分页所有信息的 IPage 对象
        IPage<VTaskPackages> pageResult = ivTaskPackagesService.page(page, queryWrapper);

        // 注意：为了提高性能，我们不再在这里查询每个任务包的订单详情。
        // 列表页通常只需要展示任务包的概要信息。订单详情可以在点击详情时再加载。
        // 如果您确实需要在列表页展示少量订单，我们可以在之后再优化加上。

        return Result.OK(pageResult);
    }
    @Autowired
    private VDeliverymanInfoMapper mapper;
    @RequestMapping("deliveryman")
    public Result getDeliverymanInfo() {
        String token = ThreadLocalUtil.get();
        Map<String, Object> map = JwtService.getClaimsMap(token);
        DeliveryMen men = deliveryMenMapper.selectOne(new QueryWrapper<DeliveryMen>().eq("user_id", (Integer)map.get("id")));
        return Result.OK(mapper.selectOne(new QueryWrapper<VDeliverymanInfo>().eq("deliveryman_id", men.getId())));
    }
    private Integer mapStatusToCode(String status) {
        if (status == null) {
            return null;
        }
        switch (status) {
            case "pending":
                return 0; // 待接单
            case "delivering":
                return 1; // 配送中
            case "completed":
                return 2; // 已完成
            case "cancelled":
                return 3; // 已取消
            default:
                // 如果传来未知的状态，可以返回null，这样就不会应用这个筛选条件
                return null;
        }
    }
    @PostMapping("/completeByPackage")
    public Result completeByPackage(@RequestParam("packageId") String packageId) {
        ordersService.completeOrdersByPackageId(packageId);
        return Result.OK("任务包已完成");
    }

    @GetMapping("/package/uncollectedList")
    public Result getUncollectedPackagesByDeliveryman(@RequestParam Integer deliverymanId) {
        String token = ThreadLocalUtil.get();
        Map<String, Object> map = JwtService.getClaimsMap(token);
        DeliveryMen men = deliveryMenMapper.selectOne(new QueryWrapper<DeliveryMen>().eq("user_id", (Integer)map.get("id")));
        Integer deliverymanId1 = men.getId(); // 此处为示例，请务必替换
        List<VTaskPackageOrders> list = deliveryTasksService.getUncollectedPackagesByDeliveryman(deliverymanId1);
        return Result.OK(list);
    }
    @Autowired
    private ExceptionTypeDictMapper extypeMapper;
    @Autowired
    private ExceptionSeverityDictMapper exseverityMapper;
    @RequestMapping("extypelist")
    public Result getExceptionTypeList() {
        List<ExceptionTypeDict> list = extypeMapper.selectList(null);
        return Result.OK(list);
    }
    @RequestMapping("exseverity")
    public Result getExceptionSeverityList() {
        List<ExceptionSeverityDict> list = exseverityMapper.selectList(null);
        return Result.OK(list);
    }
    @PostMapping("/cancel")
    public Result cancelTaskPackage(@RequestBody Map<String, String> params) {
        String packageId = params.get("packageId");
        if (packageId == null) {
            return Result.ERROR("参数缺失");
        }
        boolean success = deliveryTasksService.cancelTaskPackage(packageId);
        return success ? Result.OK("取消成功") : Result.ERROR("取消失败");
    }
    @GetMapping("task-package-stats")
    public Result getTaskPackageStats() {
        Map<String, Long> stats = ivTaskPackagesService.getTaskPackageStats();
        return Result.OK(stats);
    }
    //揽收
    @PostMapping("/collect/{packageId}")
    public Result collectPackage(@PathVariable String packageId) {
        boolean ok = deliveryTasksService.collectPackageAndOrders(packageId);
        return ok ? Result.OK() : Result.ERROR("揽收失败");
    }
    //接单逻辑
    @PostMapping("/acceptTaskPackage")
    public Result acceptTaskPackage(@RequestBody AcceptTaskRequest request) {

        // =================================================================
        // ↓↓↓ **重要**: 在这里获取当前登录的配送员ID ↓↓↓
        // =================================================================
        // 这部分逻辑需要您根据项目的用户认证方式（如Session, Spring Security, Sa-Token等）来实现
        // String deliverymanId = ... 从Session或Token中获取用户ID ...;
        String token = ThreadLocalUtil.get();
        Map<String, Object> map = JwtService.getClaimsMap(token);
        DeliveryMen men = deliveryMenMapper.selectOne(new QueryWrapper<DeliveryMen>().eq("user_id", (Integer)map.get("id")));
        String deliverymanId = String.valueOf(men.getId()); // 此处为示例，请务必替换
        // =================================================================

        // 调用服务层执行接单逻辑
        boolean success = deliveryTasksService.acceptTask(request.getPackageId(), deliverymanId);

        if (success) {
            return Result.OK("接单成功！");
        } else {
            return Result.ERROR("接单失败，任务可能已被别人抢先一步或当前状态已更新。");
        }
    }


    @PostMapping("/read")
    public Result markAsRead(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        boolean updated = notificationService.markAsRead(id);
        return updated ? Result.OK() : Result.ERROR("操作失败");
    }

    @PostMapping("/readAll")
    public Result markAllAsRead(@RequestBody(required = false) Map<String, Object> params) {
        // 假设有登录用户ID
        String token = ThreadLocalUtil.get();
        Map<String, Object> map = JwtService.getClaimsMap(token);
        DeliveryMen men = deliveryMenMapper.selectOne(new QueryWrapper<DeliveryMen>().eq("user_id", (Integer)map.get("id")));
        Long deliverymanId = Long.valueOf(men.getId());
        boolean updated = notificationService.markAllAsRead(deliverymanId);
        return updated ? Result.OK() : Result.ERROR("操作失败");
    }
}
